const http = require('http');
const formidable = require('formidable');

const items = [];

const server = http.createServer(function (req, res) {
  switch (req.method) {
    case 'GET':
      show(res);
      break;
    case 'POST':
      upload(req, res);
      break;
  }
});
server.listen(3000, function () {
  console.log('http://localhost:3000');
});

function show(res) {
  const html = `
<html>
<head>
<title>Todo List</title>
</head>
<body>
  <h1>Todo List</h1>
  <ul>
    ${items
      .map(function (item) {
        return '<li>' + item + '</li>';
      })
      .join('')}
  </ul>
  <form method="post" action="/" enctype="multipart/form-data">
    <p>
      <input type="text" name="name" >
    </p>
    <p>
      <input type="file" name="file" >
    </p>
    <p>
      <input type="submit" value="Upload" >
    </p>
  </form>
</body>
</html>
`;
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Content-Length', Buffer.byteLength(html));
  res.end(html);
}

function upload(req, res) {
  if (!isFormData(req)) {
    res.statusCode = 400;
    res.end('Bad Request: expecting multipart/form-data');
    return;
  }
  const form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.statucCode = 400;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Bad Request');
    }
    console.log(fields);
    console.log(files);
    res.end('upload complete!');
  });
}

function isFormData(req) {
  const type = req.headers['content-type'] || '';
  return type.indexOf('multipart/form-data') == 0;
}
